package util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUpLoad {
	private List<FileItem> items;

	public FileUpLoad(HttpServletRequest request) {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
		try {
			this.items = servletFileUpload.parseRequest(request);
		} catch (FileUploadException e) {
			throw new RuntimeException("上传数据失败!", e);
		}
	}

	public String getValue(String fieldName) {
		for (FileItem item : items) {
			if (fieldName.equals(item.getFieldName())) {
				try {
					return item.getString("UTF-8");
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException("获取数据失败!", e);
				}
			}
		}
		return null;
	}
	
	public List getValues(String fieldName) {
		List ids=new ArrayList();
		for (FileItem item : items) {
			if (fieldName.equals(item.getFieldName())) {
				try {
					ids.add(item.getString("UTF-8"));
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException("获取数据失败!", e);
				}
			}
		}
		return ids;
	}
	public FileItem getFileItem(String fieldName) {
		for(FileItem item : items) {
			if(!item.isFormField()) {
				if(fieldName.equals(item.getFieldName())) {
					return item;
				}
			}
		}
		return null;
	}
	
	public List<FileItem> getFileItemList(String fieldName) {
		List<FileItem> fileItems = new ArrayList<FileItem>();
		for(FileItem item : items) {
			if(!item.isFormField()) {
				if(fieldName.equals(item.getFieldName())) {
					fileItems.add(item);
				}
			}
		}
		return fileItems;
	}
}
